package com.example.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/workflow")
@Tag(name = "工作流管理", description = "业务流程和工作流管理")
public class WorkflowController {

    // ==================== 工作流定义 ====================
    @GetMapping("/definitions")
    @Operation(summary = "获取工作流定义列表")
    public ResponseEntity<List<Map<String, Object>>> getWorkflowDefinitions() {
        List<Map<String, Object>> definitions = List.of(
            Map.of(
                "id", 1L,
                "name", "订单处理流程",
                "key", "order_process",
                "version", 1,
                "description", "从订单创建到完成的完整流程",
                "isActive", true,
                "createdAt", "2024-11-01 10:00:00"
            ),
            Map.of(
                "id", 2L,
                "name", "质检流程",
                "key", "quality_check",
                "version", 1,
                "description", "洗护完成后的质检流程",
                "isActive", true,
                "createdAt", "2024-11-01 10:30:00"
            ),
            Map.of(
                "id", 3L,
                "name", "退款流程",
                "key", "refund_process",
                "version", 1,
                "description", "客户退款申请处理流程",
                "isActive", true,
                "createdAt", "2024-11-01 11:00:00"
            )
        );
        
        return ResponseEntity.ok(definitions);
    }

    @PostMapping("/definitions")
    @Operation(summary = "创建工作流定义")
    public ResponseEntity<Map<String, Object>> createWorkflowDefinition(
            @Valid @RequestBody Map<String, Object> definitionData) {
        
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "工作流定义创建成功");
        response.put("id", 1L);
        return ResponseEntity.ok(response);
    }

    @PutMapping("/definitions/{id}")
    @Operation(summary = "更新工作流定义")
    public ResponseEntity<Map<String, Object>> updateWorkflowDefinition(
            @PathVariable Long id,
            @Valid @RequestBody Map<String, Object> definitionData) {
        
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "工作流定义更新成功");
        return ResponseEntity.ok(response);
    }

    @DeleteMapping("/definitions/{id}")
    @Operation(summary = "删除工作流定义")
    public ResponseEntity<Void> deleteWorkflowDefinition(@PathVariable Long id) {
        return ResponseEntity.ok().build();
    }

    // ==================== 工作流实例 ====================
    @GetMapping("/instances")
    @Operation(summary = "获取工作流实例列表")
    public ResponseEntity<Page<Map<String, Object>>> getWorkflowInstances(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String definitionKey) {
        
        Pageable pageable = PageRequest.of(page, size, Sort.by("startTime").descending());
        
        // 模拟工作流实例数据
        List<Map<String, Object>> instances = List.of(
            Map.of(
                "id", "instance_001",
                "definitionKey", "order_process",
                "definitionName", "订单处理流程",
                "businessKey", "LO20241201001",
                "status", "RUNNING",
                "currentTask", "质检确认",
                "startTime", "2024-12-01 10:30:00",
                "assignee", "张三"
            ),
            Map.of(
                "id", "instance_002",
                "definitionKey", "quality_check",
                "definitionName", "质检流程",
                "businessKey", "QC20241201001",
                "status", "COMPLETED",
                "currentTask", "已完成",
                "startTime", "2024-12-01 09:15:00",
                "endTime", "2024-12-01 10:20:00",
                "assignee", "李四"
            )
        );
        
        Page<Map<String, Object>> instancePage = Page.empty(pageable);
        return ResponseEntity.ok(instancePage);
    }

    @PostMapping("/instances/start")
    @Operation(summary = "启动工作流实例")
    public ResponseEntity<Map<String, Object>> startWorkflowInstance(
            @RequestBody Map<String, Object> startData) {
        
        String definitionKey = (String) startData.get("definitionKey");
        String businessKey = (String) startData.get("businessKey");
        
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "工作流实例启动成功");
        response.put("instanceId", "instance_" + System.currentTimeMillis());
        response.put("definitionKey", definitionKey);
        response.put("businessKey", businessKey);
        
        return ResponseEntity.ok(response);
    }

    @GetMapping("/instances/{instanceId}")
    @Operation(summary = "获取工作流实例详情")
    public ResponseEntity<Map<String, Object>> getWorkflowInstance(@PathVariable String instanceId) {
        Map<String, Object> instance = new HashMap<>();
        instance.put("id", instanceId);
        instance.put("definitionKey", "order_process");
        instance.put("definitionName", "订单处理流程");
        instance.put("businessKey", "LO20241201001");
        instance.put("status", "RUNNING");
        instance.put("startTime", "2024-12-01 10:30:00");
        
        // 流程历史
        instance.put("history", List.of(
            Map.of("taskName", "订单确认", "assignee", "系统", "startTime", "2024-12-01 10:30:00", "endTime", "2024-12-01 10:31:00", "status", "COMPLETED"),
            Map.of("taskName", "分配工人", "assignee", "调度员", "startTime", "2024-12-01 10:31:00", "endTime", "2024-12-01 10:35:00", "status", "COMPLETED"),
            Map.of("taskName", "洗护处理", "assignee", "张三", "startTime", "2024-12-01 10:35:00", "endTime", "2024-12-01 14:20:00", "status", "COMPLETED"),
            Map.of("taskName", "质检确认", "assignee", "李四", "startTime", "2024-12-01 14:20:00", "status", "RUNNING")
        ));
        
        return ResponseEntity.ok(instance);
    }

    @PostMapping("/instances/{instanceId}/suspend")
    @Operation(summary = "暂停工作流实例")
    public ResponseEntity<Map<String, Object>> suspendWorkflowInstance(@PathVariable String instanceId) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "工作流实例已暂停");
        return ResponseEntity.ok(response);
    }

    @PostMapping("/instances/{instanceId}/resume")
    @Operation(summary = "恢复工作流实例")
    public ResponseEntity<Map<String, Object>> resumeWorkflowInstance(@PathVariable String instanceId) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "工作流实例已恢复");
        return ResponseEntity.ok(response);
    }

    @PostMapping("/instances/{instanceId}/terminate")
    @Operation(summary = "终止工作流实例")
    public ResponseEntity<Map<String, Object>> terminateWorkflowInstance(
            @PathVariable String instanceId,
            @RequestBody Map<String, String> terminateData) {
        
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "工作流实例已终止");
        return ResponseEntity.ok(response);
    }

    // ==================== 任务管理 ====================
    @GetMapping("/tasks")
    @Operation(summary = "获取待办任务列表")
    public ResponseEntity<Page<Map<String, Object>>> getTasks(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String assignee,
            @RequestParam(required = false) String status) {
        
        Pageable pageable = PageRequest.of(page, size, Sort.by("createTime").descending());
        
        // 模拟任务数据
        List<Map<String, Object>> tasks = List.of(
            Map.of(
                "id", "task_001",
                "name", "质检确认",
                "description", "对订单LO20241201001进行质检确认",
                "assignee", "李四",
                "status", "PENDING",
                "priority", "HIGH",
                "dueDate", "2024-12-01 18:00:00",
                "createTime", "2024-12-01 14:20:00",
                "instanceId", "instance_001",
                "businessKey", "LO20241201001"
            ),
            Map.of(
                "id", "task_002",
                "name", "退款审批",
                "description", "处理客户退款申请",
                "assignee", "王五",
                "status", "PENDING",
                "priority", "MEDIUM",
                "dueDate", "2024-12-02 12:00:00",
                "createTime", "2024-12-01 15:30:00",
                "instanceId", "instance_003",
                "businessKey", "RF20241201001"
            )
        );
        
        Page<Map<String, Object>> taskPage = Page.empty(pageable);
        return ResponseEntity.ok(taskPage);
    }

    @GetMapping("/tasks/{taskId}")
    @Operation(summary = "获取任务详情")
    public ResponseEntity<Map<String, Object>> getTask(@PathVariable String taskId) {
        Map<String, Object> task = new HashMap<>();
        task.put("id", taskId);
        task.put("name", "质检确认");
        task.put("description", "对订单LO20241201001进行质检确认");
        task.put("assignee", "李四");
        task.put("status", "PENDING");
        task.put("priority", "HIGH");
        task.put("dueDate", "2024-12-01 18:00:00");
        task.put("createTime", "2024-12-01 14:20:00");
        
        // 任务表单
        task.put("formData", Map.of(
            "orderId", "LO20241201001",
            "customerName", "张三",
            "serviceType", "干洗",
            "qualityScore", "",
            "notes", ""
        ));
        
        return ResponseEntity.ok(task);
    }

    @PostMapping("/tasks/{taskId}/complete")
    @Operation(summary = "完成任务")
    public ResponseEntity<Map<String, Object>> completeTask(
            @PathVariable String taskId,
            @RequestBody Map<String, Object> taskData) {
        
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "任务完成成功");
        response.put("nextTask", "配送安排");
        
        return ResponseEntity.ok(response);
    }

    @PostMapping("/tasks/{taskId}/claim")
    @Operation(summary = "认领任务")
    public ResponseEntity<Map<String, Object>> claimTask(@PathVariable String taskId) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "任务认领成功");
        return ResponseEntity.ok(response);
    }

    @PostMapping("/tasks/{taskId}/delegate")
    @Operation(summary = "委派任务")
    public ResponseEntity<Map<String, Object>> delegateTask(
            @PathVariable String taskId,
            @RequestBody Map<String, String> delegateData) {
        
        String assignee = delegateData.get("assignee");
        
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "任务委派成功");
        response.put("newAssignee", assignee);
        
        return ResponseEntity.ok(response);
    }

    // ==================== 工作流统计 ====================
    @GetMapping("/statistics")
    @Operation(summary = "获取工作流统计")
    public ResponseEntity<Map<String, Object>> getWorkflowStatistics() {
        Map<String, Object> statistics = new HashMap<>();
        
        // 实例统计
        statistics.put("totalInstances", 1250L);
        statistics.put("runningInstances", 85L);
        statistics.put("completedInstances", 1150L);
        statistics.put("suspendedInstances", 15L);
        
        // 任务统计
        statistics.put("totalTasks", 2500L);
        statistics.put("pendingTasks", 120L);
        statistics.put("completedTasks", 2350L);
        statistics.put("overdueTasks", 30L);
        
        // 效率统计
        statistics.put("averageProcessingTime", 24.5); // 小时
        statistics.put("onTimeCompletionRate", 92.5);  // 百分比
        statistics.put("taskCompletionRate", 94.0);    // 百分比
        
        // 流程分布
        statistics.put("processDistribution", List.of(
            Map.of("process", "订单处理流程", "count", 850, "percentage", 68.0),
            Map.of("process", "质检流程", "count", 250, "percentage", 20.0),
            Map.of("process", "退款流程", "count", 150, "percentage", 12.0)
        ));
        
        return ResponseEntity.ok(statistics);
    }
}
